package com.rf.richfitwheel.workflow.rabbitmq;

import com.rf.richfitwheel.workflow.entity.WorkflowMsgVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;

@Component
public class WorkflowSender implements RabbitTemplate.ConfirmCallback, ReturnCallback {

    private static final Logger log = LoggerFactory.getLogger(WorkflowSender.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("消息唯一标识：{},确认结果：{},失败原因：{}", correlationData, ack, cause);

    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("消息主体 message : {},消息主体 message : {},描述：{}, 消息使用的交换器 exchange : {}, 消息使用的路由键 routing : {}", message, replyCode, replyText, exchange, routingKey);
    }

    //发送消息，不需要实现任何接口，供外部调用。
    @Async
    public void sendWorkflowMsg(WorkflowMsgVo workflowMsgVo) {
        if (StringUtils.isNotBlank(workflowMsgVo.getQueueName())) {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            //System.out.println("开始发送消息 : " + msgVo);
            rabbitTemplate.convertSendAndReceive("workflowTopicExchange", workflowMsgVo.getQueueName(), workflowMsgVo, correlationId);
            //System.out.println("结束发送消息 : " + msgVo);
            //System.out.println("消费者响应 : " + response + " 消息处理完成");
        }

    }
}